package com.onenine.app.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.manager.OssManager;
import com.google.android.flexbox.FlexboxLayout;
import com.onenine.app.R;
import com.onenine.app.activity.BrowserImageActivity;
import com.onenine.app.activity.DynamicListActivity;
import com.onenine.app.activity.EditInfoActivity;
import com.onenine.app.activity.RechargeActivity;
import com.onenine.app.activity.SettingActivity;
import com.onenine.app.activity.WithdrawActivity;
import com.onenine.app.event.AppUpdateEvent;
import com.onenine.app.event.ConnectStatusEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.listener.OnConnectStatusListener;
import com.onenine.app.model.UserGiftItem;
import com.onenine.app.request.CommonRequest;
import com.onenine.app.request.HeadPicSubmitRequest;
import com.onenine.app.response.GetUserGiftResponse;
import com.onenine.app.response.MyAccountResponse;
import com.onenine.app.response.UserInfoResponse;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.SpCommonHelper;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.dialog.QuitLoginDialog;
import com.onenine.app.view.popwin.AvatarPopWindow;
import com.onenine.app.view.pulltozoomview.PullToZoomBase;
import com.onenine.app.view.pulltozoomview.PullToZoomScrollViewEx;
import com.onenine.base.base.BaseEventFragment;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.CircleIndicatorView;
import com.onenine.base.view.NiceImageView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.chat.rongcloud.UserCacheMgr;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.SizeUtils;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 个人中心-我的
 */
public class MineFragment extends BaseEventFragment implements View.OnClickListener, ViewPager.OnPageChangeListener
        , PullToZoomBase.OnPullZoomListener, OnBannerListener, EasyPermissions.PermissionCallbacks, OssManager.Callback, PullToZoomScrollViewEx.OnScrollYChangedListener {

    private static final String[] CAMERA_PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    protected static final int REQ_OPEN_CAMERA = 189;
    private TextView mTvName, mTvNameSmall, mTvAge, mTvAgeSmall, mTvHometown, mTvNetStatus,
            mTvSpecialSign, mTvUpdateBubble, mTvDiamond, mTvCoin, mTvRank;
    private Banner mBanner;
    private NiceImageView mImgAvatar, mImgAvatarSmall;
    private View mBtnSetting;
    private FlexboxLayout mFbLabel, mFbObject, mFbHobby, mFbGetGift, mFbOutGift;
    private PullToZoomScrollViewEx mPullScrollView;
    private Button mBtnRecharge, mBtnWithdraw;
    private View mZoomImg, mTitleBar;
    private CircleIndicatorView mIndicatorView;
    private ImageButton mBtnDynamic, mBtnEdit;
    private ArrayList<String> mImgList = new ArrayList<>();
    private int mHeadViewHeight;

    @Override
    protected int getLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(View view) {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        mPullScrollView = view.findViewById(R.id.sv_pull_to);
        View vHead = layoutInflater.inflate(R.layout.layout_mine_head, null, false);
        View vContent = layoutInflater.inflate(R.layout.layout_mine_content, null, false);
        mZoomImg = layoutInflater.inflate(R.layout.layout_mine_zoom_img, null, false);
        mPullScrollView.setHeaderView(vHead);
        mPullScrollView.setZoomView(mZoomImg);
        mPullScrollView.setScrollContentView(vContent);
        mHeadViewHeight = getResources().getDimensionPixelOffset(R.dimen.mine_album_banner_height);
        mIndicatorView = vHead.findViewById(R.id.civ_indicator);
        RelativeLayout.LayoutParams headParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mHeadViewHeight);
        mPullScrollView.setHeaderLayoutParams(headParams);
        RelativeLayout.LayoutParams covParams = (RelativeLayout.LayoutParams) vContent.getLayoutParams();
        covParams.topMargin = getResources().getDimensionPixelOffset(R.dimen.mine_content_top_margin);
        mPullScrollView.setContentLayoutParams(covParams);
        mImgAvatar = vContent.findViewById(R.id.iv_headpic);
        mImgAvatarSmall = view.findViewById(R.id.iv_headpic_small);
        mTvName = vContent.findViewById(R.id.tv_name);
        mTvNameSmall = view.findViewById(R.id.tv_name_small);
        mTvAge = vContent.findViewById(R.id.tv_age);
        mTvAgeSmall = view.findViewById(R.id.tv_age_small);
        mTvNetStatus = vContent.findViewById(R.id.tv_net_status);
        mTvHometown = vContent.findViewById(R.id.tv_hometown);
        mTvSpecialSign = vContent.findViewById(R.id.tv_special_sign);
        mBtnSetting = vContent.findViewById(R.id.btn_setting);
        mFbLabel = vContent.findViewById(R.id.fb_my_label);
        mFbObject = vContent.findViewById(R.id.fb_my_object);
        mFbHobby = vContent.findViewById(R.id.fb_my_hobby);
        mFbGetGift = vContent.findViewById(R.id.fb_get_gift);
        mFbOutGift = vContent.findViewById(R.id.fb_out_gift);
        mTvDiamond = vContent.findViewById(R.id.tv_my_diamond_num);
        mTvCoin = vContent.findViewById(R.id.tv_my_coin_num);
        mTvRank = vContent.findViewById(R.id.tv_my_rank_value);
        mBtnDynamic = vContent.findViewById(R.id.btn_my_dynamic);
        mTvUpdateBubble = vContent.findViewById(R.id.tv_bubble);
        mTvUpdateBubble.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.CIRCLE_POINT_BUBBLE));
        mBtnRecharge = vContent.findViewById(R.id.btn_recharge);
        mBtnWithdraw = vContent.findViewById(R.id.btn_withdraw);
        mBanner = vHead.findViewById(R.id.banner);
        mBanner.setImageLoader(new GlideImageLoader());
        mBtnEdit = view.findViewById(R.id.btn_edit);
        mTitleBar = view.findViewById(R.id.vw_title_bar);
        mTitleBar.setBackgroundColor(RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        mBtnRecharge.setTextColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        mBtnRecharge.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_STROKE_WHITE_CORNER));
        mBtnWithdraw.setTextColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        mBtnWithdraw.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_STROKE_WHITE_CORNER));
        StatusBarUtils.setTransparentForImageViewInFragment(getActivity(), null);
    }

    @Override
    public void onStart() {
        super.onStart();
        getMyAccount();
        getUserGifts();
        mBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        mBanner.stopAutoPlay();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            StatusBarUtils.setFullScreenLightMode(getActivity());
        } else {
            StatusBarUtils.setTransparentForImageViewInFragment(getActivity(), null);
            UserInfoResponse userInfo = RcUser.getInstance().getInfoResponse();
            if (userInfo == null) {
                getPersonalInfo();
            } else {
                showInfoView(userInfo);
                showLabels(userInfo);
                startImageBanner(userInfo.getAlbum());
            }
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mBtnSetting.setOnClickListener(this);
        mBtnDynamic.setOnClickListener(this);
        mBanner.setOnBannerListener(this);
        mBanner.setOnPageChangeListener(this);
        mImgAvatar.setOnClickListener(this);
        mImgAvatarSmall.setOnClickListener(this);
        mTitleBar.setOnClickListener(this);
        mPullScrollView.setOnPullZoomListener(this);
        mPullScrollView.setOnScrollYChangedListener(this);
        mBtnRecharge.setOnClickListener(this);
        mBtnWithdraw.setOnClickListener(this);
        mBtnEdit.setOnClickListener(this);
    }

    /**
     * 获取当前用户资产信息
     */
    private void getMyAccount() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_ACCOUNT)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(MineFragment.class.getSimpleName(), new OkCallback<MyAccountResponse>() {
                    @Override
                    public void onResponse(MyAccountResponse response, String srcData) {
                        if (response.isSuccess()) {
                            mTvDiamond.setText(response.getAvailableDiamond() + "");
                            mTvCoin.setText(response.getAvailableGold() + "");
                            mTvCoin.setTag(response.getAvailableGold());
                            mTvRank.setText(response.getLevelName());
                        }
                    }
                });
    }

    /**
     * 获取当前用户礼物
     */
    private void getUserGifts() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_MY_GIFT)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(MineFragment.class.getSimpleName(), new OkCallback<GetUserGiftResponse>() {
                    @Override
                    public void onResponse(GetUserGiftResponse response, String srcData) {
                        if (response.isSuccess()) {
                            showGiftLabel(mFbGetGift, response.getGetGift());
                            showGiftLabel(mFbOutGift, response.getOutGift());
                        }
                    }
                });
    }

    /**
     * 获取当前用户信息
     */
    private void getPersonalInfo() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_PERSONAL_INFO)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(MineFragment.class.getSimpleName(), new OkCallback<UserInfoResponse>() {
                    @Override
                    public void onResponse(UserInfoResponse response, String srcData) {
                        if (response.isSuccess()) {
                            RcUser.getInstance().setInfoResponse(response);
                            showInfoView(response);
                            showLabels(response);
                            startImageBanner(response.getAlbum());
                        }
                    }
                });
    }

    /**
     * 显示个人资料详情
     *
     * @param response
     */
    private void showInfoView(UserInfoResponse response) {
        final int avatarSize = ApUtils.getApp().getResources().getDimensionPixelSize(R.dimen.avatar_size_62dp);
        final int avatarSizeSmall = ApUtils.getApp().getResources().getDimensionPixelSize(R.dimen.avatar_size_40dp);
        GlideUtils.loadSrcImage(ApUtils.getApp(), mImgAvatar, CHelper.getOssThumbImageUrl(response.getPhoto(), avatarSize));
        GlideUtils.loadSrcImage(ApUtils.getApp(), mImgAvatarSmall, CHelper.getOssThumbImageUrl(response.getPhoto(), avatarSizeSmall));
        mTvName.setText(response.getNickName());
        mTvNameSmall.setText(response.getNickName());
        mTvHometown.setText(response.getProvinceName() + " " + response.getCityName());
        mBtnDynamic.setImageResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_M_DYNAMIC, response.getSex()));
        if ("".equals(response.getPersonSign())) {
            mTvSpecialSign.setHint(R.string.no_special_sign_default);
        } else {
            mTvSpecialSign.setText(response.getPersonSign());
        }
        mTvAge.setVisibility(View.VISIBLE);
        mTvAge.setCompoundDrawablesWithIntrinsicBounds(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_SEX_WHITE), 0, 0, 0);
        mTvAge.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SHAPE_MINE_SEX_AGE_BG));
        mTvAge.setText(response.getAge() + "");
        mTvAgeSmall.setCompoundDrawablesWithIntrinsicBounds(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_SEX_WHITE), 0, 0, 0);
        mTvAgeSmall.setText(response.getAge() + "");
    }

    /**
     * 显示标签组
     *
     * @param response
     */
    private void showLabels(UserInfoResponse response) {
        showLabelView(mFbLabel, response.getMylabelNames());
        showLabelView(mFbObject, response.getIdealObjectLabelNames());
        showLabelView(mFbHobby, response.getUniqueHobbyLabelNames());
    }

    /**
     * 显示礼物标签
     *
     * @param flexboxLayout
     * @param giftItemList
     */
    public void showGiftLabel(FlexboxLayout flexboxLayout, List<UserGiftItem> giftItemList) {
        if (giftItemList.isEmpty()) {
            return;
        }
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        flexboxLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(ApUtils.getApp());
        for (UserGiftItem giftItem : giftItemList) {
            View view = layoutInflater.inflate(R.layout.layout_user_gift_item, null, false);
            ImageView ivIcon = view.findViewById(R.id.iv_gift_icon);
            TextView tvNum = view.findViewById(R.id.tv_gift_num);
            GlideUtils.loadSrcImage(ApUtils.getApp(), ivIcon, giftItem.getGiftIcon());
            tvNum.setText(" x " + giftItem.getGiftNum());
            tvNum.setTextColor(RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR1, RcUser.getInstance().getSex()));
            flexboxLayout.addView(view);
        }
    }

    /**
     * 启动头像加相册banner
     *
     * @param albumStr
     */
    private void startImageBanner(String albumStr) {
        if (mBanner != null) {
            mBanner.releaseBanner();
            mBanner.stopAutoPlay();
        }
        mImgList.clear();
        if (!TextUtils.isEmpty(albumStr)) {
            String[] albums = albumStr.split(",");
            for (String album : albums) {
                mImgList.add(album);
            }
        }
        mBanner.setImages(mImgList);
        mBanner.start();
        if (mImgList.size() > 1) {
            mIndicatorView.playTo(mImgList.size(), 0);
            mIndicatorView.setVisibility(View.VISIBLE);
        } else {
            mIndicatorView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_headpic:
            case R.id.iv_headpic_small:
                //头像
                new AvatarPopWindow(getActivity(), new AvatarPopWindow.Callback() {
                    @Override
                    public void onViewAvatar() {
                        UserInfoResponse userInfo = RcUser.getInstance().getInfoResponse();
                        if (userInfo == null
                                || TextUtils.isEmpty(userInfo.getPhoto())) {
                            return;
                        }
                        BrowserImageActivity.launchActivity(getActivity(), userInfo.getPhoto());
                    }

                    @Override
                    public void onEditAvatar() {
                        if (EasyPermissions.hasPermissions(getContext(), CAMERA_PERMISSIONS)) {
                            launchAlbum();
                        } else {
                            EasyPermissions.requestPermissions(MineFragment.this, getString(R.string.permission_camera_hint)
                                    , REQ_OPEN_CAMERA, CAMERA_PERMISSIONS);
                        }
                    }
                }).showPopWindow();
                break;
            case R.id.btn_setting:
                SettingActivity.launchActivity(getActivity()
                        , mTvUpdateBubble.getVisibility() == View.VISIBLE);
                break;
            case R.id.btn_edit:
                if (RcUser.getInstance().getInfoResponse() != null) {
                    EditInfoActivity.launchActivity(getActivity());
                } else {
                    getPersonalInfo();
                    Toasty.showNormal(R.string.info_load_fail_un_edit);
                }
                break;
            case R.id.btn_my_dynamic:
                UserInfoResponse infoResponse = RcUser.getInstance().getInfoResponse();
                if (infoResponse != null) {
                    DynamicListActivity.launchActivity(getActivity()
                            , RcUser.getInstance().getUserId(), infoResponse.getBackgroundPicture());
                }
                break;
            case R.id.btn_recharge:
                //我的钻石
                RechargeActivity.launchActivity(getActivity());
                break;
            case R.id.btn_withdraw:
                WithdrawActivity.launchActivity(getActivity());
                //我的金币
                break;
        }
    }

    /**
     * 准备加载相册
     */
    protected void launchAlbum() {
        int size = AppConfig.SCREEN_WIDTH / 3 - SizeUtils.dp2px(10);
        Matisse.from(this)
                .choose(MimeType.ofImage())//显示照片
                .countable(false)//无序选择图片
                .capture(true)
                .captureStrategy(new CaptureStrategy(true
                        , ApUtils.getApp().getPackageName() + ".fileprovider"))
                .showSingleMediaType(true)//只显示一种媒体类型，此处只会显示图片，过滤了视频
                .maxSelectable(1)//最大选择数量为1
                .gridExpectedSize(size)//图片显示表格的大小getResources()
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(101);//请求码
    }

    /**
     * 显示标签组
     *
     * @param flexboxLayout
     * @param labelNameStr
     */
    public void showLabelView(FlexboxLayout flexboxLayout, String labelNameStr) {
        if (TextUtils.isEmpty(labelNameStr)) {
            return;
        }
        String[] labels = labelNameStr.split(",");
        int labelMargin = SizeUtils.dp2px(5);
        flexboxLayout.removeAllViews();
        for (String label : labels) {
            TextView tvLabel = (TextView) getLayoutInflater().inflate(R.layout.layout_my_label_item, null, false);
            tvLabel.setText(label);
            tvLabel.setBackgroundResource(R.drawable.shape_mine_label_bg);
            tvLabel.setTextColor(ActivityCompat.getColor(getContext(), R.color.c999));
            tvLabel.setTextSize(11);
            FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout
                    .LayoutParams(FlexboxLayout.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelOffset(R.dimen.dp22));
            layoutParams.setMargins(labelMargin, labelMargin, labelMargin, labelMargin);
            flexboxLayout.addView(tvLabel, -1, layoutParams);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.type == DataType.REFRESH_USER_INFO) {
            getPersonalInfo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppUpdateEvent event) {
        if (event.updateStatus == DataType.APP_UPDATE) {
            if (!SpCommonHelper.getInstance().isAppVersionMd5Equal(event.newVersionNum)) {
                mTvUpdateBubble.setVisibility(View.VISIBLE);
            }
        } else if (event.updateStatus == DataType.APP_CLEAR_UPDATE) {
            mTvUpdateBubble.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ConnectStatusEvent event) {
        Logger.e("登录状态：" + event.getMsg());
        if (OnConnectStatusListener.RC_KICKED_OFFLINE_BY_OTHER_CLIENT.equals(event.getMsg())) {
            //登录失效，在其它设备登录了
            CDataProcessor.quitAppAndReLogin(getActivity(), false);
            new QuitLoginDialog(ActivityUtils.getTopActivity()
                    , OnConnectStatusListener.RC_KICKED_OFFLINE_BY_OTHER_CLIENT).show();
        } else if (OnConnectStatusListener.RC_CONNECTED.equals(event.getMsg())) {
            //在线
            mTvNetStatus.setText(R.string.online);
            mTvNetStatus.setBackgroundResource(R.drawable.shape_online_corner_bg);
        } else if (OnConnectStatusListener.RC_CONNECTING.equals(event.getMsg())) {
            //连接中
            mTvNetStatus.setText(R.string.connecting);
            mTvNetStatus.setBackgroundResource(R.drawable.shape_connecting_corner_bg);
        } else {
            //离线
            mTvNetStatus.setText(R.string.offline);
            mTvNetStatus.setBackgroundResource(R.drawable.shape_offline_corner_bg);
        }
    }

    @Override
    public void OnBannerClick(int position) {
        BrowserImageActivity.launchActivity(getActivity(), mImgList, position);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 101) {
                compressImages(Matisse.obtainPathResult(data));
            }
        }
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param images
     */
    private void compressImages(List<String> images) {
        Luban.with(getActivity())
                .load(images).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        OssManager.getInstance(ApUtils.getApp())
                                .ossUpload(file.getPath(), MineFragment.this);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    public void onSuccess(String url) {
        HeadPicSubmitRequest request = new HeadPicSubmitRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPhoto(url);
        OkRequest.getInstance().withUrl(UrlConfig.UPLOAD_HEADPIC).withRequest(request)
                .doRequest(getClass().getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            UserCacheMgr.getInstance().deleteUserCacheByUserId(request.getUserId());
                            getPersonalInfo();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
        Logger.e("头像上传失败：" + errorCode + "," + errorMsg);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == REQ_OPEN_CAMERA
                && CAMERA_PERMISSIONS.length == perms.size()) {
            launchAlbum();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == REQ_OPEN_CAMERA) {
            Toasty.showNormal(R.string.permission_camera_hint);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        GlideUtils.loadSrcImage(ApUtils.getApp()
                , (ImageView) mZoomImg, mImgList.get(position));
        mIndicatorView.playTo(mImgList.size(), position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPullZooming(int newScrollValue) {
        if (mImgList.isEmpty()) {
            return;
        }
        if (mBanner.getVisibility() == View.VISIBLE) {
            mBanner.stopAutoPlay();
            mBanner.releaseBanner();
            mBanner.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPullZoomEnd() {

    }

    @Override
    public void onPullZoomFinish() {
        if (mImgList.isEmpty()) {
            return;
        }
        if (mBanner.getVisibility() != View.VISIBLE) {
            mBanner.setVisibility(View.VISIBLE);
            mBanner.startAutoPlay();
        }
    }

    @Override
    public void onScrollChanged(float scrollY) {
        float alpha = scrollY / mHeadViewHeight;
        if (alpha >= 1.0f) {
            if (mImgAvatarSmall.getVisibility() != View.VISIBLE) {
                mTitleBar.setAlpha(0.8f);
                if (!TextUtils.isEmpty(mTvName.getText())) {
                    mImgAvatarSmall.setVisibility(View.VISIBLE);
                    mTvNameSmall.setVisibility(View.VISIBLE);
                    mTvAgeSmall.setVisibility(View.VISIBLE);
                }
            }
        } else {
            if (alpha >= 0.8f) {
                mTitleBar.setAlpha(0.8f);
            } else {
                mTitleBar.setAlpha(0.0f);
            }
            if (mImgAvatarSmall.getVisibility() == View.VISIBLE) {
                if (!TextUtils.isEmpty(mTvName.getText())) {
                    mImgAvatarSmall.setVisibility(View.GONE);
                    mTvNameSmall.setVisibility(View.GONE);
                    mTvAgeSmall.setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 图片加载器
     */
    private class GlideImageLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            GlideUtils.loadSrcImage(context, imageView, (String) path);
        }
    }

}
